﻿using Abp.BackgroundJobs;
using Abp.Dependency;
using Abp.Events.Bus.Handlers;
using Abp.ObjectMapping;
using AVIS.OutBound.BookOrders;
using AVIS.OutBound.CarGroups.Job;
using AVIS.OutBound.Orders;
using AVIS.OutBound.RateCodes.Cache;
using AVIS.OutBound.WizardAgent;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AVIS.OutBound.CarGroups
{
    /// <summary>
    /// 发起异步请求来同步更新车组信息并缓存到Redis
    /// </summary>
    public class SyncCarGroupsEventHandler :
        IEventHandler<BookOrderSaveCompletedEventData>,
        IEventHandler<CarGroupPriceChangedEventData>,
        ITransientDependency
    {
        #region 构造函数
        private readonly IBookOrderManager _bookOrderManager;
        private readonly IObjectMapper _objectMapper;
        private readonly IRateCodeManager _rateCodeMananger;
        private readonly IBackgroundJobManager _backgroundJobManager;
        private readonly WizardVehAvailRateAgent _wizardVehAgent;


        public SyncCarGroupsEventHandler(
            IBookOrderManager bookOrderManager,
            IObjectMapper objectMapper,
            IRateCodeManager rateCodeMananger,
            IBackgroundJobManager backgroundJobManager
            )
        {
            _bookOrderManager = bookOrderManager;
            _objectMapper = objectMapper;
            _rateCodeMananger = rateCodeMananger;
            _backgroundJobManager = backgroundJobManager;
            _wizardVehAgent = new WizardVehAvailRateAgent();
        }
        #endregion

        /// <summary>
        /// 异步请求预订单下一步的车组汇总信息（多个套餐的车组信息）
        /// </summary>
        /// <param name="eventData"></param>
        public void HandleEvent(BookOrderSaveCompletedEventData eventData)
        {
            var bookOrder = _bookOrderManager.GetBookOrder(eventData.OrderId);
            if (bookOrder == null
                || bookOrder.PickupDateTime.Ticks == 0
                || bookOrder.ReturnDateTime.Ticks == 0
                || string.IsNullOrWhiteSpace(bookOrder.PickUpStoreCode)
                || string.IsNullOrWhiteSpace(bookOrder.ReturnStoreCode))
            {
                return;
            }

            // 获取满足订单的套餐价格代码（最新的4条）
            var RatePackages = _rateCodeMananger.GetRateCodesByOrder(bookOrder);
            for (var i = RatePackages.Count - 1; i >= 0; i--)
            {
                var args = _objectMapper.Map<WizardCarGroupsJobArgs>(bookOrder);
                args.RateCode = RatePackages[i].Code;

                // 判断缓存是否存在
                if (!_wizardVehAgent.CarGroupsExistsInCache(_objectMapper.Map<CarGroupsRequest>(args)))
                {
                    // 发起异步请求队列，更新车组信息
                    _backgroundJobManager.Enqueue<WizardCarGroupsJob, WizardCarGroupsJobArgs>(args);
                }
            }
        }

        /// <summary>
        /// 车组价格发生变化，需要发起异步请求更新指定车组的信息
        /// </summary>
        /// <param name="eventData"></param>
        public void HandleEvent(CarGroupPriceChangedEventData eventData)
        {
            var bookOrder = _bookOrderManager.GetBookOrder(eventData.OrderId);
            var args = _objectMapper.Map<WizardCarGroupsJobArgs>(bookOrder);

            // 从缓存中清除指定RateCode的车组信息
            _wizardVehAgent.RemoveCarGroupsCache(_objectMapper.Map<CarGroupsRequest>(args));

            // 发起异步请求队列，更新车组信息
            _backgroundJobManager.Enqueue<WizardCarGroupsJob, WizardCarGroupsJobArgs>(args);
        }
    }
}
